import 'dart:convert';
import 'dart:io';

import 'package:sl_doclever/src/utils/sl_consts.dart';
import 'package:sl_doclever/src/utils/sl_templete.dart';
import 'package:sl_doclever/src/utils/sl_utils.dart';

import '../../sl_doclever.dart';

class SLDocRAC {
  Map dataMap;
  Map outMap;

  String rac_mtd;
  String rac_mtd_invoke;
  String rac_mtd_dis;
  String rac_properties;
  String rac_subNext;

  RACInfo racInfo;

  final SLObjcHttp http;

  SLDocRAC(this.http) {
    dataMap = {};

    racInfo = http.rac_all_request();

    // replace keywords
    var mtdL = [], mtdUse = [], cmdL = [], mtdDis = [], cmdSub = [];
    racInfo.mtdL.forEach((http) {
      var r = SL_DOC_MTD.replaceAll('[DOCLEVER_M_DESC]', http.desc);
      r = r.replaceAll('[DOCLEVER_OBJC]', http.cmd);
      r = r.replaceAll('[DOCLEVER_M_OBJ]', racInfo.name);
      r = r.replaceAll('[DOCLEVER_MTD]', http.mtd);

      mtdL.add(r);
      mtdUse.add('// ${http.desc}\n' '[self seg_${http.cmd}];');
      cmdL.add('/// ${http.desc}\n'
          '@property (nonatomic, strong) RACCommand *${http.cmd};');
      mtdDis
          .add('// ${http.desc}\n' '[self.${http.cmd} rac_deallocDisposable];');
      cmdSub.add(http.subNext);
    });

    // data bind
    rac_mtd = mtdL.join('\n');
    rac_mtd_invoke = mtdUse.join('\n');
    rac_properties = cmdL.join('\n');
    rac_mtd_dis = mtdDis.join('\n');
    rac_subNext = cmdSub.join('\n');

    dataMap['cls'] = racInfo.cls;
    dataMap['singleTone'] = racInfo.singleTone;
    dataMap['name'] = racInfo.name;

    dataMap['mtd'] = rac_mtd;
    dataMap['mtd_invoke'] = rac_mtd_invoke;
    dataMap['mtd_dis'] = rac_mtd_dis;
    dataMap['properties'] = rac_properties;
    dataMap['sub'] = rac_subNext;

    outMap = outFiles();
  }

  void saveToLocal(String path) {
    if (dataMap == null || dataMap.isEmpty) return;
    File(path).writeAsStringSync(json.encode(dataMap));
  }

  Map outFiles() {
    var out = {};

    var vmName = racInfo.cls.endsWith('Manager')
        ? racInfo.cls.replaceAll('Manager', 'ViewModel')
        : 'ViewModel';

    out['$vmName.h'] = sl_doc_RACCommand_h;
    out['$vmName.m'] = sl_doc_RACCommand_m;

    var result = {};
    out.forEach((key, value) {
      value = value.replaceAll('[IN_NAME_MANAGER]', racInfo.cls);
      value = value.replaceAll('[IN_NAME_MANAGER_NAME]', racInfo.name);
      value = value.replaceAll('[DATE]', SLUtils.dateString);
      value = value.replaceAll('[IN_NAME]', vmName);
      value = value.replaceAll('[IN_PROPERTY]', rac_properties);
      value = value.replaceAll('[VM_IM_PROPERTY_DIS]', rac_mtd_dis);
      value = value.replaceAll('[VM_IM_CMD_USE]', rac_mtd_invoke);
      value = value.replaceAll('[VM_IM_CMD]', rac_mtd);

      result[key] = value;
    });

    return result;
  }

  @override
  String toString() => 'rac_mtd:$rac_mtd,'
      'rac_mtd_invoke:$rac_mtd_invoke,'
      'rac_properties:$rac_properties\n';
}
